package com.zuoyeben123.testzybhtml.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * Created by wangliang on 2017/11/27.
 */

public class ImageUtils {

    public static byte[] bitmapToByte(Bitmap bm) {
        if(bm != null) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
            byte[] datas = baos.toByteArray();
            try {
                baos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return datas;
        }
        return null;
    }

    public static Bitmap byteToBitmap(byte[] data) {
        if(data != null) {
            return BitmapFactory.decodeByteArray(data, 0, data.length);
        }
        return null;
    }

    public static Bitmap zoomBitmap(Bitmap bitmap, int maxWidth,
                                        int maxHeight) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        Matrix matrix = new Matrix();

        float scale = 1.0f;
        if (width < height) { // 宽度小于高度
            if (height > maxHeight) {
                scale = (float) maxHeight / height;
            }
        } else {
            if (width > maxWidth) {
                scale = (float) maxWidth / width;
            }
        }
        if (scale != 1.0f) {
            matrix.postScale(scale, scale);
            Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, width, height,
                    matrix, true);
            return newbmp;
        } else {
            return bitmap;
        }
    }
}
